package net.citrite.android;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import java.util.*;

import static com.android.SdkConstants.*;

public class XPathBuilder {
    private static final javax.xml.xpath.XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
    private static final AndroidNamespaceContext context = new AndroidNamespaceContext();
    public static XPath newXPath() {
        XPath xpath = factory.newXPath();
        xpath.setNamespaceContext(context);
        return xpath;
    }

    private static class AndroidNamespaceContext implements NamespaceContext {
        private final Map<String, String> prefixMap = new HashMap<String, String>() {
            {
                put(ANDROID_NS_NAME, ANDROID_URI);
                put(TOOLS_PREFIX, TOOLS_URI);
            }
        };

        public String getNamespaceURI(String prefix) {
            if (prefix == null) {
                throw new NullPointerException("No prefix provided");
            }
            if (prefixMap.containsKey(prefix)) {
                return prefixMap.get(prefix);
            }
            return XMLConstants.NULL_NS_URI;
        }

        public String getPrefix(String namespaceURI) {
            if (namespaceURI == null)
                return null;
            for (Map.Entry<String, String> item : prefixMap.entrySet()) {
                if (namespaceURI.equals(item.getValue())) {
                    return item.getKey();
                }
            }
            return null;
        }

        public Iterator<?> getPrefixes(String namespaceURI) {
            if (namespaceURI == null)
                return null;
            if (prefixMap.containsValue(namespaceURI)) {
                return prefixMap.keySet().iterator();
            }
            return null;
        }
    }

}
